package com.shenhaofeng.app.component.dialog.task;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.annotation.CallSuper;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.view.View;

import java.io.Serializable;


/**
 * 延时加载弹窗,类似于ContentLoadingProgress,延时弹出弹窗或延时销毁弹窗，可以获取更好的交互体验
 * Created by 沈豪烽 on 2016/9/21.
 */
public class DelayedLoadingDialogFragment<R> extends AsyncTaskDialogFragment<R> {

    //loading最少的显示时间
    private static final int MIN_SHOW_TIME = 500; // ms

    //loading时间少于该值将不会显示loading界面
    private static final int MIN_DELAY = 500; // ms

    //主线程handle
    private Handler mHandler=new Handler();

    //启动show的启动时间,记录延时时间
    private long mShowStartTime = -1;

    //关闭Dialog的启动时间,记录延时时间
    private long mDismissStartTime = -1;

    //记录是否已提交Dismiss的任务请求
    private boolean mPostedDismiss = false;

    //记录是否已提交Show的任务请求
    private boolean mPostedShow = false;

    //标记了显示状态
    private boolean mDismissed;

    private boolean isShowing = false;


    private R mDelayedResult;

    private Throwable mDelayedThrowable;







    /**
     * 延时显示loading界面
     */
    private final Runnable showRunnable = new Runnable() {
        @Override
        public void run() {
            //标记
            mPostedShow = false;
            //标记显示状态为显示中
            isShowing = true;
            if (getShowsDialog()) {
                //将状态切换为显示
                getDialog().show();
            } else {
                // TODO: 2016/9/22
            }
        }
    };


    /**
     * 延时后的销毁
     */
    private final Runnable hideRunnable = new Runnable() {
        @Override
        public void run() {
            mPostedDismiss = false;
            isShowing = false;
            if (getShowsDialog()) {
                if (mDelayedResult != null) {
                    DelayedLoadingDialogFragment.super.onHandleResult(getListener(), mDelayedResult);
                    return;
                }
                if (mDelayedThrowable != null) {
                    DelayedLoadingDialogFragment.super.onHandleFailure(getListener(), mDelayedThrowable);
                    return;
                }
                dismiss();
            }
        }
    };


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }



    @Override
    public void onPause() {
        super.onPause();
    }


    @Override
    public void onResume() {
        super.onResume();
        if (mDelayedResult != null) {
            return;
        }
        if (mDelayedThrowable != null) {
            return;
        }
        if (mDismissed) {
            dismiss();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mHandler.removeCallbacks(showRunnable);
        mHandler.removeCallbacks(hideRunnable);
    }


    @Override
    public void onShow(DialogInterface dialog) {
        if(getDialog()==null){
            return;
        }
        if (!isShowing) {
            if (getShowsDialog()) {
                //dialog的处理方法
                getDialog().hide();
            } else {
                // TODO: 2016/9/22
            }
        }
    }




    @CallSuper
    @Override
    public void dismiss() {
        super.dismiss();
        mDismissed = true;
        removeAllCallback();
    }


    @Override
    protected void onExecuteShow(FragmentManager fragmentManager, String tag) {
        super.onExecuteShow(fragmentManager, tag);
        removeAllCallback();
        mDismissed = false;
        //记录启动时间
        mShowStartTime = System.currentTimeMillis();
        //标记显示中为false
        isShowing = false;
        mPostedShow = true;
        //发送一个延时任务
        mHandler.postDelayed(showRunnable, MIN_DELAY);
    }


    @Override
    protected void onHandleResult(Listener<R> listener, R result) {
        if (mPostedShow) {
            mHandler.removeCallbacks(showRunnable);
            super.onHandleResult(listener, result);
        } else {
            mDelayedResult = result;
            mPostedDismiss = true;
            mHandler.postDelayed(hideRunnable, MIN_SHOW_TIME);
        }
    }


    @Override
    protected void onHandleFailure(Listener<R> listener, Throwable throwable) {
        if (mPostedShow) {
            mHandler.removeCallbacks(showRunnable);
            super.onHandleFailure(listener, throwable);
        } else {
            mDelayedThrowable = throwable;
            mPostedDismiss = true;
            mHandler.postDelayed(hideRunnable, MIN_SHOW_TIME);
        }
    }


    private void removeAllCallback() {
        mHandler.removeCallbacks(showRunnable);
        mHandler.removeCallbacks(hideRunnable);
        mDelayedResult = null;
        mDelayedThrowable = null;
    }



}
